package com.zyp.dao;

import com.zyp.entity.Account;
import com.zyp.entity.Transaction;
import com.zyp.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class AccountDao {

    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    //实现卡号：1122334455向55443332211转账5000元的操作；

    //进行判断转账金额是否充足,充足就进行转账，不充足就取消转账
    public Account judgmentAmount(Transaction transaction) throws SQLException {

        String sql = "select * from account where card = ?";

        Account account = qr.query(sql, new BeanHandler<Account>(Account.class), transaction.getCardid());
        System.out.println(account.toString());
        if (account.getBalance() > transaction.getTramoney()) {//判断交易的余额是否充足
            return account;
        }
        return null;
    }

    //进行账号的转出
    public int updateTransferIn(Transaction transaction) throws SQLException {
        String sql = "UPDATE account SET balance=balance-? WHERE card=?";
        Object[] param = {transaction.getTramoney(), transaction.getCardid()};
        int update = qr.update(sql, param);
        return update;
    }

    //进行账号的转入
    public int updateTransferOut(Transaction transaction) throws SQLException {
        String sql = "UPDATE account SET balance=balance+? WHERE card=?";
        Object[] param = {transaction.getTramoney(), transaction.getCardid()};
        int update = qr.update(sql, param);
        return update;
    }
}
